import { userData } from "@/store/userData";
import { advanceOrder,makeOrder,checkPayStatu } from "@/api/api";
import {showLoading,closeLoading} from '@/utils/utils'

const wait = (time:number)=>{
    return new Promise((resolve, reject)=>{
        if(!time){
            resolve(true)
        }else{
            setTimeout(()=>{
                resolve(true)
            },time)
        }
        
    })
}



const state = {
    slimType:null, //  1 开会员  2 入群
    totalAmt:null, // 金额
    productId:null, // 入群时为群id,
    preId:null,
    orderId:'',
    payType:null,
    checkNum:0,
    chancel:false,
}

const init = ()=>{
    state.slimType = null;
    state.totalAmt = null;
    state.productId = null;
    state.preId = null;
    state.orderId = '';
    state.payType = null;
    state.checkNum = 0;
    state.chancel = false;
}


const AdvanceOrder = async()=>{

    const USER_DATA = userData();

    const params = {
        userId:USER_DATA.id,
        slimType:Number(state.slimType),
        totalAmt:Number(state.totalAmt),
        productId:state.productId,
    }

    const res:any = await advanceOrder(params);
    const {flag,message} = res;
    if(flag!==1){
        uni.showToast({
            icon: "none",
            title: message,
            duration: 3000,
        });
        closeLoading();
        return 
    }
    state.preId = res.data.merOrderId;
}


const MakeOrder = async()=>{
    const params = {
        merOrderId:state.preId,
        payType:state.payType,
    }

    const res:any = await makeOrder(params);
    const {flag,message} = res;
    if(flag!==1){
        uni.showToast({
            title: message,
            duration: 3000,
        });
        closeLoading();
        return 
    }
    state.orderId = res.data.payParam;
}



const openZhifubao = ()=>{
    //checkStatu();
    return new Promise((resolve, reject)=>{
        uni.getProvider({
            service: 'payment',
            success: function (res:any) {
                if (~res.provider.indexOf('alipay')) {
                    uni.requestPayment({
                        "provider": "alipay",   //固定值为"alipay"
                        "orderInfo": state.orderId, //此处为服务器返回的订单信息字符串
                        success: (res)=> {
                            console.log("支付成功");
                            console.log(rawdata);
                            var rawdata = JSON.parse(res.rawdata);
                            resolve(rawdata)
                        },
                        fail: function (err) {
                            closeLoading();
                            uni.showToast({
                                icon: "none",
                                title: '支付未完成',
                                duration: 3000,
                            });

                            state.chancel = true;

                            reject(err);
                            console.log('支付失败:' + JSON.stringify(err));
                        }
                    });
                }
            }
        });

    })
}
const openWeixin = ()=>{
    //checkStatu();

    return new Promise((resolve, reject)=>{
        uni.getProvider({
            service: 'payment',
            success: function (res:any) {
                if (~res.provider.indexOf('wxpay')) {
                    uni.requestPayment({
                        "provider": "wxpay",   //固定值为"alipay"
                        "orderInfo": JSON.parse(state.orderId), //此处为服务器返回的订单信息字符串
                        success: (res)=> {
                            console.log("支付成功");
                            console.log(rawdata);
                            var rawdata = JSON.parse(res.rawdata);
                            resolve(rawdata)
                        },
                        fail: function (err) {
                            closeLoading();
                            uni.showToast({
                                icon: "none",
                                title: '支付未完成',
                                duration: 3000,
                            });
                            state.chancel = true;
                            reject(err);
                            console.log('支付失败:' + JSON.stringify(err));
                        }
                    });
                }
            }
        });

    })
}

const openPayApp = async()=>{
    if(Number(state.payType)===1){
        // uni.showToast({
        //     icon: "none",
        //     title: '暂不支持微信支付',
        //     duration: 3000,
        // });
        // closeLoading();
        // return false;
        return await openWeixin();
    }
    if(Number(state.payType)===2){
        return await openZhifubao();
    }
}

const checkStatu:any = async()=>{

    if(state.chancel){
        return Promise.reject('取消')
    }

    if(state.checkNum>=33){
        return Promise.reject('超时');
    }

    state.checkNum +=1;
    const res:any = await checkPayStatu({merOrderId:state.preId}).catch((err)=>{
        console.log('eeeeeeeeeeee')
        console.log('eeeeeeeeeeee')
        console.log('eeeeeeeeeeee')
        console.log(err)
    })

    if(!res){
        await wait(2000);

        return await checkStatu();
    }

    const {flag,message,data} = res;




    if(flag!==1){
        await wait(2000);

        return await checkStatu();
    }

    const { payStatus } = data;

    if(payStatus!==1){

        await wait(2000);
        return await checkStatu();

    }


    // uni.showToast({
    //         icon: "none",
    //         title: message||'支付成功!',
    //         duration: 3000,
    // });
    return Promise.resolve(true);
}


export const pay = async ( {slimType,totalAmt,productId,payType}:any)=>{
    init();
    if(!slimType||!totalAmt||!productId||!payType){
        uni.showToast({
            icon: "none",
            title: '支付参数有误，请检查',
            duration: 3000,
        });
        return;
    }
    state.slimType = slimType;
    state.totalAmt = totalAmt;
    state.productId = productId;
    state.payType = payType;

    await AdvanceOrder();
	if(state.preId == null)return;
    await MakeOrder();
    openPayApp();
    const result = await checkStatu();
    return result

}

